using net_work.Data.DTO.Appr;
using net_work.Data.Enum.Appr;
using NRules.Fluent.Dsl;

namespace net_work.Rules.Appr;

public class ApprovalRuleNumber : Rule
{
    public override void Define()
    {
        Name("审批规则：Number");

        ApprovalSubmitInfo? submitInfo = null;

        When()
            .Match(() => submitInfo,
                s => s != null &&
                     s.SuccessType == NodeSuccessType.Number &&
                     s.SuccessConfig != null &&
                     s.HasHandled == false);

        Then().Do(context => UpdateApprovalSubmitInfo(submitInfo))
            .Do(context => context.Update(submitInfo));
    }

    private static void UpdateApprovalSubmitInfo(ApprovalSubmitInfo? submitInfo)
    {
        if (submitInfo?.SuccessConfig == null)
        {
            return;
        }

        var requiredApprovalCount = submitInfo.SuccessConfig.Value;

        // 判断已通过审批是否达到指定数量
        if (submitInfo.ApprovedCount >= requiredApprovalCount)
        {
            submitInfo.IsSkip = true;
            submitInfo.SkipResult = true;
            submitInfo.HasHandled = true;
            return;
        }

        // 判断任务总数是否不足以满足指定通过数量
        if (requiredApprovalCount < submitInfo.TaskTotalCount - submitInfo.UnApprovedCount)
        {
            submitInfo.HasHandled = true;
            return;
        }

        submitInfo.IsSkip = true;
        submitInfo.SkipResult = false;
        submitInfo.HasHandled = true;
    }
}